<template>
    <div class="search-bar">
        <el-form :inline="true" >

            <el-form-item label="名称">
                    <el-input v-model="filter.name" placeholder="名称" />
                </el-form-item>
                <el-form-item label="价格"> 
                    <el-input v-model="filter.price" placeholder="价格" />
                </el-form-item>

                <el-form-item>
                        <el-button type="primary" @click="do_search">搜索</el-button>
                    </el-form-item>
        </el-form> 

    </div>
    <el-table
        :data="productList"
        highlight-current-row
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            property="id"
            label="ID"
            width="80">
        </el-table-column>
        <el-table-column
            property="image"
            label="图片"
            width="">
            <template #default="scope">
                <img style="width:100%" :src="scope.row.image" alt="">
            </template>    
        </el-table-column>
        <el-table-column
            property="name"
            label="名称"
            width="">
        </el-table-column>

        
        <el-table-column
            property="brand_name"
            label="品牌"
            width="">
        </el-table-column>

        <el-table-column
            property="category_name"
            label="分类"
            width="">
           
        </el-table-column>

        <el-table-column
            property="start_at"
            label="商品型号"
            width="">
        </el-table-column>

        <el-table-column
            property="price"
            label="价格"
            width="">
        </el-table-column>

        <el-table-column
            property="sale"
            label="销量"
            width="">
           
        </el-table-column>
        <el-table-column
            property="status"
            label="状态"
            width="">
            <template #default="scope">
                <span v-if="scope.row.status==1">启用</span>
                <span v-if="scope.row.status==0">弃用</span>
            </template>   
        </el-table-column>
        <el-table-column
            align="center"
            label="操作"
            width="300">
            <template #default="scope">

                <a class="el-button el-button--primary el-button--small"
                   :href="'#/main/product/edit/' + scope.row.id">
                    编辑
                </a>
                <el-button 
                    v-if="scope.row.status == 1"
                    type="warning" 
                    size="small"
                    @click="handleOffSale(scope.row)">
                    下架
                </el-button>
                <el-button 
                    v-if="scope.row.status == 0"
                    type="success" 
                    size="small"
                    @click="handleOnSale(scope.row)">
                    上架
                </el-button>
                <el-button 
                    type="danger" 
                    size="small"
                    @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>

    </el-table>

    <div class=" table-below ">
        <a class="el-button el-button--primary"
           href="#/main/product/create">添加</a>
        <el-button 
            type="success" 
            :disabled="multipleSelection.length === 0"
            @click="handleBatchOnSale">批量上架 ({{ multipleSelection.length }})</el-button>
        <el-button 
            type="warning" 
            :disabled="multipleSelection.length === 0"
            @click="handleBatchOffSale">批量下架 ({{ multipleSelection.length }})</el-button>
        <el-button 
            type="danger" 
            :disabled="multipleSelection.length === 0"
            @click="handleBatchDelete">批量删除 ({{ multipleSelection.length }})</el-button>
        <el-pagination
            @current-change="changePage"
            :page-size="per_page"
            layout="prev, pager, next" :total="total" />
    </div>

</template>

<script lang="ts" setup>

import {ref} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";


const total:any = ref<number>(10)
const per_page:any = ref<number>(15)
const current_page:any = ref<number>(1)

const productList:any = ref<object>();
const filter:any = ref<object>({

    name:'',
    status:'',
    price:'',
    category_name:'',
    brand_name:'',
});
const multipleSelection:any = ref<any[]>([]);

const get_product_list = ()=>{

    var url:any = window.VITE_URL + '/admin.goods/get_list';

    if( filter.value.name ){
        url += '&name=' + filter.value.name;
    }
    if( filter.value.status!= '' ) {
        url += '&status=' + filter.value.status;
    }
    if( filter.value.price ){
        url += '&price=' + filter.value.price;
    }
    if( filter.value.category_name ){
        url += '&category_name=' + filter.value.category_name;
    }

    if( filter.value.brand_name ){
        url += '&brand_name=' + filter.value.brand_name;
    }

    axios.get( url ).then(function( res ){

        productList.value = res.data;
        // t.page.item_total = res.data.length;
        let string:number = res.data.length / per_page.value
        total.value = parseInt( string.toString() );
        total.value += res.data.length % per_page.value ? 1 : 0;

    });

}

get_product_list();

const changePage = ( e:number ):void => {

    current_page.value = e;

}

const do_search = ()=>{

    // console.log(' do search ');
    get_product_list();
}

const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val;
};

const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        `确定要删除商品"${row.name}"吗？删除后可以在回收站中恢复。`,
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 调用删除API，传递ids参数
        const url = window.VITE_URL + '/admin.goods/remove';
        axios.post(url, {
            ids: [row.id]
        }).then((res) => {
            if (res.data.status === 0) {
                ElMessage.success('删除成功');
                // 刷新列表
                get_product_list();
            } else {
                ElMessage.error(res.data.msg || '删除失败');
            }
        }).catch((error) => {
            ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message));
        });
    }).catch(() => {
        // 用户取消删除
    });
};

const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要删除的商品');
        return;
    }
    
    const ids = multipleSelection.value.map((item: any) => item.id);
    const names = multipleSelection.value.map((item: any) => item.name).join('、');
    
    ElMessageBox.confirm(
        `确定要删除选中的 ${ids.length} 个商品吗？\n${names}\n\n删除后可以在回收站中恢复。`,
        '确认批量删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 调用删除API，传递ids数组
        const url = window.VITE_URL + '/admin.goods/remove';
        axios.post(url, {
            ids: ids
        }).then((res) => {
            if (res.data.status === 0) {
                ElMessage.success(`成功删除 ${ids.length} 个商品`);
                // 清空选择
                multipleSelection.value = [];
                // 刷新列表
                get_product_list();
            } else {
                ElMessage.error(res.data.msg || '删除失败');
            }
        }).catch((error) => {
            ElMessage.error('删除失败：' + (error.response?.data?.msg || error.message));
        });
    }).catch(() => {
        // 用户取消删除
    });
};

// 单个上架
const handleOnSale = (row: any) => {
    ElMessageBox.confirm(
        `确定要上架商品"${row.name}"吗？`,
        '确认上架',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }
    ).then(() => {
        const url = window.VITE_URL + '/admin.goods/onSale';
        axios.post(url, {
            ids: row.id
        }).then((res) => {
            if (res.data.status === 0) {
                ElMessage.success('上架成功');
                get_product_list();
            } else {
                ElMessage.error(res.data.msg || '上架失败');
            }
        }).catch((error) => {
            ElMessage.error('上架失败：' + (error.response?.data?.msg || error.message));
        });
    }).catch(() => {
        // 用户取消
    });
};

// 单个下架
const handleOffSale = (row: any) => {
    ElMessageBox.confirm(
        `确定要下架商品"${row.name}"吗？`,
        '确认下架',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const url = window.VITE_URL + '/admin.goods/offSale';
        axios.post(url, {
            ids: row.id
        }).then((res) => {
            if (res.data.status === 0) {
                ElMessage.success('下架成功');
                get_product_list();
            } else {
                ElMessage.error(res.data.msg || '下架失败');
            }
        }).catch((error) => {
            ElMessage.error('下架失败：' + (error.response?.data?.msg || error.message));
        });
    }).catch(() => {
        // 用户取消
    });
};

// 批量上架
const handleBatchOnSale = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要上架的商品');
        return;
    }
    
    const ids = multipleSelection.value.map((item: any) => item.id);
    const names = multipleSelection.value.map((item: any) => item.name).join('、');
    
    ElMessageBox.confirm(
        `确定要上架选中的 ${ids.length} 个商品吗？\n${names}`,
        '确认批量上架',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
        }
    ).then(() => {
        const url = window.VITE_URL + '/admin.goods/onSale';
        axios.post(url, {
            ids: ids
        }).then((res) => {
            if (res.data.status === 0) {
                ElMessage.success(`成功上架 ${ids.length} 个商品`);
                multipleSelection.value = [];
                get_product_list();
            } else {
                ElMessage.error(res.data.msg || '上架失败');
            }
        }).catch((error) => {
            ElMessage.error('上架失败：' + (error.response?.data?.msg || error.message));
        });
    }).catch(() => {
        // 用户取消
    });
};

// 批量下架
const handleBatchOffSale = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要下架的商品');
        return;
    }
    
    const ids = multipleSelection.value.map((item: any) => item.id);
    const names = multipleSelection.value.map((item: any) => item.name).join('、');
    
    ElMessageBox.confirm(
        `确定要下架选中的 ${ids.length} 个商品吗？\n${names}`,
        '确认批量下架',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const url = window.VITE_URL + '/admin.goods/offSale';
        axios.post(url, {
            ids: ids
        }).then((res) => {
            if (res.data.status === 0) {
                ElMessage.success(`成功下架 ${ids.length} 个商品`);
                multipleSelection.value = [];
                get_product_list();
            } else {
                ElMessage.error(res.data.msg || '下架失败');
            }
        }).catch((error) => {
            ElMessage.error('下架失败：' + (error.response?.data?.msg || error.message));
        });
    }).catch(() => {
        // 用户取消
    });
};
</script>

<style scoped>

</style>